<template>
    <div>
       <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>添加商品</el-breadcrumb-item>
</el-breadcrumb> <br>
<el-card>
     <el-alert
    title="添加商品信息"
    type="info"
    show-icon
    :closable="false"
    center
    >
  </el-alert> <br> 
  <el-steps :active="active * 1" finish-status="success" align-center> 
  <el-step title="基本信息"></el-step>
  <el-step title="商品参数"></el-step>
  <el-step title="商品属性"></el-step>
  <el-step title="商品图片"></el-step>
  <el-step title="商品内容"></el-step>
  <el-step title="完成"></el-step> 
</el-steps> <br> 

 <el-form :model="ruleForm" :rules="rules">
    <el-tabs 
          tab-position="left" 
          v-model="active"
          @tab-click="handleClick"
          :before-leave="beforeLeave">
    <el-tab-pane label="用户管理">
          <el-form-item label="商品名称" prop="goods_name">
               <el-input v-model="ruleForm.goods_name"></el-input>
         </el-form-item>
         <el-form-item label="商品价格" prop="goods_price">
               <el-input v-model="ruleForm.goods_price"></el-input>
         </el-form-item>
         <el-form-item label="商品重量" prop="goods_weight">
               <el-input v-model="ruleForm.goods_weight"></el-input>
         </el-form-item>
         <el-form-item label="商品数量" prop="goods_number">
               <el-input v-model="ruleForm.goods_number"></el-input>
         </el-form-item> 
         <el-form-item>
              <div class="block">
                  商品分类
            <el-cascader
                v-model="valuecateData" 
                :options="cateData"
                :props="defaultProps"
                ></el-cascader>
</div>
         </el-form-item>
    </el-tab-pane>
    <el-tab-pane label="商品参数"> 
       <el-form-item   :label="item1.attr_name"  v-for="item1 in manyParams" :key="item1.id">
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox :label="item2" v-for="(item2,index) in item1.attr_vals" :key="index"></el-checkbox>
              </el-checkbox-group>  
            </el-form-item> 
    </el-tab-pane>
    <el-tab-pane label="商品属性">
        <el-form-item :label='item.attr_name' v-for="item in onlyParams" :key="item.id">  
                   <el-input v-model="item.attr_vals"></el-input>
              </el-form-item> 
    </el-tab-pane>
    <el-tab-pane label="商品图片">
         <el-upload
  action="http://www.ysqorz.top:8888/api/private/v1/upload"
  :headers="headers"
  :on-remove="handleRemove"
  :on-success="handlesuccess"
  :file-list="fileList" 
  list-type="picture"> 
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> 
</el-upload>
    </el-tab-pane>
    <el-tab-pane label="商品内容">
      <quill-editor v-model="ruleForm.goods_introduce" :options="editorOption" ></quill-editor>
<el-button type="primary" @click="addGoodsOk">添加商品</el-button>

    </el-tab-pane>
  </el-tabs>
 </el-form>
</el-card>



    </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
 import _ from "lodash" 
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      ruleForm:this.$route.query.row,
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // toggled buttons
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }], // custom button values
            [{ list: "ordered" }, { list: "bullet" }],
            [{ script: "sub" }, { script: "super" }], // superscript/subscript
            [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
            [{ direction: "rtl" }], // text direction

            [{ size: ["small", false, "large", "huge"] }], // custom dropdown
            [{ header: [1, 2, 3, 4, 5, 6, false] }],

            [{ color: [] }, { background: [] }], // dropdown with defaults from theme
            [{ font: [] }],
            [{ align: [] }],

            ["clean"]
          ]
        },
        theme: "snow",
        placeholder: "请输入正文"
      },
      fileList: [],
      headers: {
        Authorization: sessionStorage.getItem("token")
      },
      active: 0,
      cateData: [], //级联框
      valuecateData: [], //级联框选中的内容
      manyParams: [], //动态
      onlyParams: [], //静态
      defaultProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id"
      }, //级联框默认设置
    //   ruleForm: {
    //     goods_name: "",
    //     goods_price: "",
    //     goods_weight: "",
    //     goods_number: "",
    //     pics: [],
    //     goods_attrs:'' ,
    //     goods_introduce:'',
    //   },
       
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      }
    };
  }, 
  mounted() {
    this.getGoodsCateList();
  },
  methods: {

    handleChange() {},
    async handleClick() {
      console.log(this.active);
      if (this.active === "1") {
        //调取动态参数
        const res = await this.$API.getGoodsParamsApi(this.current_cate_id);
        console.log("动态传餐", res);
        res.forEach(item => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });
        this.manyParams = res;
      } else if (this.active === "2") {
        //调取静态参数
        const res = await this.$API.getGoodsParamsApi(
          this.current_cate_id,
          "only"
        );
        console.log("静态传餐", res);
        this.onlyParams = res;
      }
    },
    beforeLeave(newActive, oldActive) {
      console.log("new", newActive);
      console.log("old", oldActive);
      console.log(this.valuecateData);
      if (oldActive == 0 && this.valuecateData.length != 3) {
        this.$message({
          type: "error",
          message: "请选择三级分类之后才能进行下一步哦"
        });
        return false;
      }
    },
    //商品列表的数据
    async getGoodsCateList(){
      //获取商品分类的接口
      const  getEdit = await this.$API.bjjilianApi(this.ruleForm.goods_id); 
        console.log('1',getEdit)  
    this.valuecateData=[
          getEdit.cat_one_id,
          getEdit.cat_two_id,
          getEdit.cat_three_id
    ]
    this.ruleForm.goods_cat=[
          getEdit.cat_one_id,
          getEdit.cat_two_id,
          getEdit.cat_three_id
    ].join(',') 
    
    // const res=await this.$API.getGoodsCateApi()
    // this.ruleForm=res 

    },
    //上传图片
    handlesuccess(res) {
      console.log("成功", res);
      this.ruleForm.pics.push({ pic: res.data.tmp_path });
    },
    //删除上传
    handleRemove(res) {
      console.log("删除", res);
      const index = this.ruleForm.pics.findIndex(item => {
        return item.pic === res.response.data.tmp_path;
      }); 
      this.ruleForm.pics.splice(index, 1);
    },
    //添加商品
    async addGoodsOk(){  
      console.log('addGoodsOk:', this.ruleForm) 
      //处理分类数组为字符串
      this.ruleForm.goods_cat = this.valuecateData.join(',')
      //动态参数处理
      const dtData = this.manyParams.map((item) => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
      })
      //静态参数处理
      const jtData = this.onlyParams.map((item) => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
      }) 
      //合并静态和动态参数
      const mergeParams = [...dtData, ...jtData]
      //将合并的结果赋值给attrs
      this.ruleForm.attrs = mergeParams
      console.log('最终提交结果:', this.ruleForm)
      //将this.ruleForm对象进行深拷贝，再将深拷贝后的对象传递给后台
      const allGoodsData = _.cloneDeep(this.ruleForm)  
      //开始调添加商品接口提交数据
      const res = await this.$API.xiuaddslistApi(this.ruleForm.goods_id,allGoodsData) 
      console.log('添加成功', res)  
      //添加完商品跳转到商品列表页，查看添加的商品
      this.$router.push('/goods')
    },
  },
  computed: {
    current_cate_id() {
      return this.valuecateData[this.valuecateData.length - 1];
    }
  }
};
</script>

<style scoped >
::v-deep .ql-editor{ 
  height: 300px; 
}
</style>